import { server as WebSocketServer } from "websocket";
import http from "http";
import UserMySql from "./utils/user";
import { Ai } from "./utils/ai";
import WuziqiClass from "./utils/wuziqi";
import type { SocketDataFace } from "@/types/socket";
import sendMsgClass from "./utils/sendMsg";
import { sendAiMessage } from "./plugins/chatAi/chatAi";
import type global from "./types/global";
import { uploadImage } from "./utils/file";

//import { config } from "dotenv";
// 加载配置文件
require("dotenv").config();
const startAi: any = {};
/**
 * 环境
 */
const NODE_ENV = process.env.NODE_ENV;
console.log(NODE_ENV);
console.log(process.env.BASE_IMG_URL);
//const env = require("./config/" + NODE_ENV + ".js")

//const a:IDType='22'
const wuziqi = new WuziqiClass();
const userSql = new UserMySql();
const port = 3680;
// 创建服务器
const server = http.createServer((request, response) => {
  console.log(
    `${new Date().toLocaleDateString()} 服务器创建成功 ${request.url}`
  );
  response.writeHead(404);
  response.end();
});
server.listen(port, () => {
  console.log(`${new Date().toLocaleDateString()} 服务器端口为： ${port}`);
});
// websocket 服务器
const wsServer = new WebSocketServer({
  httpServer: server,
});

const sendMsg = new sendMsgClass(wsServer);
wsServer.on("request", (request) => {
  // 当前的连接
  console.log(request.origin, "=======连接地址=======");
  const ws = request.accept(null, request.origin);
  console.log(`${new Date().toLocaleDateString()} 已经建立连接`);
  const path = request.resourceURL.path || "";
  let userId = path.replace(/\//g, ""); // 连接后携带ID
  let myUserInfo: any = undefined; // userSql.getUserInfo(userId)!;
  // 初始化登录
  sendMsg.sendHistoryMsg(ws);

  userSql.initLogin(path, ws).then((userInfo) => {
    if (!myUserInfo) {
      myUserInfo = userInfo;
    }
    // 如果正在下棋，则发送棋盘
    if (wuziqi.status == 2) {
      sendMsg.sendWzq(wuziqi.maps, ws);
      sendMsg.sendWzqQs(wuziqi.qsList, ws);
    }
    const obj = {
      type: "online",
      msg: userInfo?.userName + "上线了",
    };
    sendMsg.broadcast(obj);
    if (!myUserInfo) return;
    if (myUserInfo?.isNew) {
      const tips = `大宝贝你好,欢迎来到群聊间，很高兴能和你相遇在这美好的夜晚，`;
      sendMsg.sendSystem(tips, ws);
      myUserInfo.isNew = false;
    } else {
      if (myUserInfo.userName && myUserInfo.userName.includes("luren")) {
        const sjs = Math.random();
        if (sjs > 0.2) {
          if (!myUserInfo.sex) {
            sendMsg.sendSystem(
              "大宝贝，你可以告诉我您的男人还是女人嘛?我想知道我是不是在聊基！",
              ws
            );
          }
        } else {
          const length = userSql.getLength() + 1;
          const newName = `大宝贝${length}号`;
          const oldName = myUserInfo.userName;
          sendMsg.sendSystem(
            "大宝贝，你怎么还不改名字呢，是不喜欢有名字么？那我帮你把名字改成大宝贝好嘛？",
            ws
          );
          setTimeout(() => {
            const tip = userSql.editName(userId, newName, false);
            const obj1 = {
              type: "userInfo",
              userName: newName,
            };
            ws.send(JSON.stringify(obj1));
            sendMsg.sendSystem(
              `由于${oldName}老不改名，被系统强行改为${newName}`
            );
          }, 2000);
        }
      }
    }
  });
  ws.on("message", (message) => {
    if (message.type === "utf8") {
      let messageData = JSON.parse(message.utf8Data);
      if (messageData.type === "ping") {
        return;
      }
      messageData.name = myUserInfo.userName;
      messageData.userId = myUserInfo.userId;

      let cmd = messageData.type;

      let { type, msg } = messageData;

      let cmdVal: any = "";
      /**
       * 语言消息AI处理归一化，至switch处理
       */
      if (cmd === "chat") {
        sendMsg.broadcast(messageData);
        const aiData = Ai(msg);
        const startAiArr = ["开启ai", "开启AI", "开启Ai"];
        const endAiArr = ["关闭ai", "关闭AI", "关闭Ai"];
        if (startAiArr.includes(msg)) {
          startAi[userId] = 1;
          sendMsg.sendSystem(
            "已经为您开启AI模式，您的每一句话，都会为您执行AI查询",
            ws
          );
        } else if (endAiArr.includes(msg)) {
          startAi[userId] = undefined;
          sendMsg.sendSystem(
            "已经为您关闭ai模式",
            ws
          );
        } else if (startAi[userId]) {
          startAi[userId]++;
          console.log("收到ai消息---");
            sendMsg.sendSystem(
               '收到了我正在查询中',
              );
          sendAiMessage(msg)
            .then((res) => {
              sendMsg.broadcast({
                type: "deepseek",
                msg: res,
              });
            })
            .catch((err) => {
              sendMsg.broadcast({
                type: "ai",
                msg: "很抱歉，我出错了",
              });
            });
          if (startAi[userId] > 10) {
            startAi[userId] = undefined;
            sendMsg.sendSystem(
              "已经超过10句，已为您关闭ai模式，请重新输入开启ai,进行操作",
              ws
            );
          }
        } else if (aiData) {
          cmd = aiData.cmd;
          cmdVal = aiData.val;
        } else {
          if (wuziqi.status == 2) {
            wuziqi.ai(msg, myUserInfo, sendMsg);
          }
          // 棋手的处理稍微复杂，单独进行处理
          // 如果正在下棋
          const startQ = ["开始下棋", "开始下五子棋", "下五子棋", "五子棋"];
          if (wuziqi.status == 1 || wuziqi.status == 3) {
            const isSome = startQ.some((v) => msg.indexOf(v) === 0);
            if (isSome) {
              wuziqi.start();
              sendMsg.sendWzq(wuziqi.maps);
              const allTip = `下五子棋非常简单。首先，我们需要一个棋盘，这是一个15×15的网格。每位玩家轮流在网格的交叉点上放置棋子，一方使用黑色棋子，另一方使用白色棋子。目标是在棋盘上先形成连续的五个棋子，可以是水平、垂直或对角线方向。`;
              let tips1 = `五子棋启动，您可以说黑棋/白棋,成为棋手，可以说A1/C6，进行下棋，\n${allTip}`;
              sendMsg.sendWzqSystem(tips1);
              return;
            }
          }
          if (wuziqi.status === 3) {
            if (msg.indexOf("继续") == 0) {
              wuziqi.start();
              sendMsg.sendWzq(wuziqi.maps);
              sendMsg.sendWzqSystem("您可以继续下棋，已经为您初始化棋盘");
              return;
            }
          }
        }
      }

      switch (cmd) {
        case "editname":
          const newName = cmdVal || msg;
          const tips = userSql.editName(userId, newName) as string;
          myUserInfo.userName = newName;
          console.log(newName)
          sendMsg.sendSystem(tips);
          break;
        case "editSex":
          userSql.editSex(userId, cmdVal);
          myUserInfo.sex = cmdVal;
          break;
        case "cmd:getPrevSex":
          const prevMsgData = sendMsg.getPrevMsg() as any;
          if (prevMsgData && prevMsgData.userId) {
            const user = userSql.getUserInfo(prevMsgData.userId);
            if (user) {
              const sexName =
                user.sex && user.sex == 1
                  ? "是男人"
                  : user.sex == 2
                  ? "是女人"
                  : "一不是男的，二不是女的";
              sendMsg.sendSystem(`${user.userName}${sexName}`);
            }
          }
          break;

        case "play":
          if (wuziqi.status != 2) {
            sendMsg.sendSystem(
              "还没有初始化棋盘 ，请输入《-wzq:》或者说，我要下五子棋，初始化棋盘"
            );
            return;
          }
          wuziqi.playMsg(msg, myUserInfo, sendMsg);
          break;
        case "ai":
        case "xinghuo":
          sendMsg.broadcast(messageData);
        case "ai":
        case "xinghuo":
        case "sound":
          sendMsg.broadcast(messageData);

        default:
          break;
      }
    } else if (message.type === "binary") {
      const length = message.binaryData.length;
      // binary 二进制

      // ws.sendBytes(message.binaryData);
      const maxLength = Number(process.env.MAX_IMG_SIZE ?? 1000000);
      if (length > maxLength) {
        sendMsg.sendSystem("图片太大,请您优化图片后发送", ws);
      } else {
        uploadImage(message.binaryData).then((url) => {
          const imgUrl = process.env.BASE_IMG_URL + url;

          sendMsg.sendChatImg({
            imgUrl,
            type: "chat",
            name: myUserInfo.userName,
            userId,
          });
        });
      }
    }
  });

  // 监听当前连接 当断开链接(网页关闭) 触发
  ws.on("close", (reasonCdoe, description) => {
    console.log(
      `${new Date().toLocaleDateString()} ${ws.remoteAddress} 断开链接`
    );

    userSql.offline(userId);
    sendMsg.sendSystem(`${myUserInfo?.userName}走了`);
  });

  ws.on("error", function (code) {
    console.log("关闭连接2", code);
    // 某些情况如果客户端多次触发连接关闭，会导致connection.close()出现异常，这里try/catch一下
    try {
      ws.close();
    } catch (error) {
      console.log("close异常", error);
    }
    console.log("异常关闭", code);
  });
});
